<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="setUpdatePassword">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>保存</template>
      </a-button>
    </template>
  </pageHeader>
  <div class="content">
    <a-form
      :model="form.data"
      :style="{ width: '600px' }"
      ref="formRef"
      :rules="rules"
    >
      <a-form-item
        tooltip="新密码以字母开头,6-12位长度"
        field="password"
        label="新密码："
      >
        <a-input v-model="form.data.password" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item field="post" label="确认新密码：">
        <a-input v-model="form.data.post" placeholder="请输入新密码" />
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, onMounted, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { updatePassword } from '@/api/user';
  import { number } from 'echarts';

  const router = useRouter();
  const title: string = '修改密码';
  const breadCrumb: string[] = ['系统管理', '基础设置', '修改密码'];
  const formRef = ref();
  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const form = reactive<any>({
    data: {
      password: '',
      post: '',
      userId: Number(userInfo.id),
      mobile: userInfo.mobile,
    },
  });

  // 新密码以字母开头,8-12位长度
  let checkNew = (value, callback) => {
    if (!value) {
      return callback(new Error('新密码不能为空'));
    } else {
      // 8-12位，以字母开头`
      let match = /^[a-zA-Z]\w{5,11}$/;
      if (!match.test(value)) {
        return callback(new Error('新密码以字母开头,6-12位长度'));
      } else {
        callback();
      }
    }
  };
  // 验证确认密码
  let checkNewOk = (value, callback) => {
    if (!value) {
      return callback(new Error('新密码不能为空'));
    } else if (value !== form.data.password) {
      return callback(new Error('新密码必须一致'));
    }
  };
  const rules = {
    password: [
      {
        required: true,
        validator: checkNew,
      },
    ],
    post: [
      {
        required: true,
        validator: checkNewOk,
      },
    ],
  };

  const setUpdatePassword = () => {
    formRef.value.validate(async (res) => {
      if (!res) {
        await updatePassword({ ...form.data });
        router.back();
      }
    });
  };
</script>

<style lang="less" scoped>
  .content {
    margin-top: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
